'use client'

import { useState, useEffect } from 'react'
import { PlusIcon, UserGroupIcon, UserIcon, TrashIcon, XMarkIcon, PencilIcon } from '@heroicons/react/24/outline'
import Button from '@/components/ui/Button'

interface User {
  id: string
  name: string | null
  email: string
}

interface GroupMember {
  id: string
  user: User
  role: string
}

interface Group {
  id: string
  name: string
  description: string | null
  members: GroupMember[]
}

interface AuthorizedExperiment {
  id: string
  student: User
}

interface Experiment {
  id: string
  title: string
  groups: Group[]
  authorizedExperiments: AuthorizedExperiment[]
}

interface GroupManagementProps {
  experiments: Experiment[]
  students: User[]
  currentUserId: string
}

export default function GroupManagement({ experiments: initialExperiments, students, currentUserId }: GroupManagementProps) {
  const [experiments, setExperiments] = useState<Experiment[]>(initialExperiments)
  const [selectedExperiment, setSelectedExperiment] = useState<string>('')
  const [showCreateGroup, setShowCreateGroup] = useState(false)
  const [showEditGroup, setShowEditGroup] = useState(false)
  const [editingGroup, setEditingGroup] = useState<Group | null>(null)
  const [groupName, setGroupName] = useState('')
  const [groupDescription, setGroupDescription] = useState('')
  const [selectedStudents, setSelectedStudents] = useState<string[]>([])
  const [selectedLeader, setSelectedLeader] = useState<string>('')
  const [loading, setLoading] = useState(false)
  const [loadingStudentId, setLoadingStudentId] = useState<string | null>(null)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')

  const currentExperiment = experiments.find(exp => exp.id === selectedExperiment)

  // 自动清除错误消息
  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => setError(''), 5000)
      return () => clearTimeout(timer)
    }
  }, [error])

  // 获取未分组的学生
  const getUnassignedStudents = () => {
    if (!currentExperiment) return students

    const assignedStudentIds = new Set<string>()
    
    // 收集已分组的学生ID
    currentExperiment.groups.forEach(group => {
      group.members.forEach(member => {
        assignedStudentIds.add(member.user.id)
      })
    })

    // 收集已授权但未分组的学生ID
    const authorizedStudentIds = new Set(
      currentExperiment.authorizedExperiments.map((authExp: AuthorizedExperiment) => authExp.student.id)
    )

    // 返回已授权但未分组的学生
    return students.filter(student => 
      authorizedStudentIds.has(student.id) && !assignedStudentIds.has(student.id)
    )
  }

  // 创建新分组
  const handleCreateGroup = async () => {
    if (!selectedExperiment || !groupName || selectedStudents.length === 0) {
      setError('请填写完整信息并选择至少一名学生')
      return
    }

    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch('/api/groups', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: groupName,
          description: groupDescription,
          experimentId: selectedExperiment,
          studentIds: selectedStudents,
          leaderId: selectedLeader || selectedStudents[0],
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '创建分组失败')
      }

      const { group } = await response.json()

      // 更新本地状态
      setExperiments(prevExperiments => 
        prevExperiments.map(exp => 
          exp.id === selectedExperiment
            ? {
                ...exp,
                groups: [...exp.groups, group]
              }
            : exp
        )
      )

      setSuccess('分组创建成功')
      setShowCreateGroup(false)
      setGroupName('')
      setGroupDescription('')
      setSelectedStudents([])
      setSelectedLeader('')
      
      // 清除成功消息
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      setError(err.message || '创建分组失败')
    } finally {
      setLoading(false)
    }
  }

  // 编辑分组
  const handleEditGroup = (group: Group) => {
    setEditingGroup(group)
    setGroupName(group.name)
    setGroupDescription(group.description || '')
    const currentLeader = group.members.find(m => m.role === 'LEADER')
    setSelectedLeader(currentLeader?.user.id || '')
    setShowEditGroup(true)
  }

  // 更新分组
  const handleUpdateGroup = async () => {
    if (!editingGroup || !groupName) {
      setError('请填写分组名称')
      return
    }

    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(`/api/groups/${editingGroup.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          name: groupName,
          description: groupDescription,
          leaderId: selectedLeader,
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '更新分组失败')
      }

      const { group } = await response.json()

      // 更新本地状态
      setExperiments(prevExperiments => 
        prevExperiments.map(exp => 
          exp.id === selectedExperiment
            ? {
                ...exp,
                groups: exp.groups.map((g: Group) => g.id === group.id ? group : g)
              }
            : exp
        )
      )

      setSuccess('分组更新成功')
      setShowEditGroup(false)
      setEditingGroup(null)
      setGroupName('')
      setGroupDescription('')
      setSelectedLeader('')
      
      // 清除成功消息
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      setError(err.message || '更新分组失败')
    } finally {
      setLoading(false)
    }
  }

  // 删除分组
  const handleDeleteGroup = async (groupId: string) => {
    if (!confirm('确定要删除这个分组吗？')) return

    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(`/api/groups/${groupId}`, {
        method: 'DELETE',
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '删除分组失败')
      }

      // 更新本地状态
      setExperiments(prevExperiments => 
        prevExperiments.map(exp => 
          exp.id === selectedExperiment
            ? {
                ...exp,
                groups: exp.groups.filter(group => group.id !== groupId)
              }
            : exp
        )
      )

      setSuccess('分组删除成功')
      // 清除成功消息
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      setError(err.message || '删除分组失败')
    } finally {
      setLoading(false)
    }
  }

  // 授权学生访问实验
  const handleAuthorizeStudents = async (studentIds: string[]) => {
    if (!selectedExperiment || studentIds.length === 0) return

    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(`/api/experiments/${selectedExperiment}/authorize`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          studentIds,
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '授权失败')
      }

      // 更新本地状态
      const authorizedExperiments = studentIds.map(studentId => {
        const student = students.find(s => s.id === studentId)
        return student ? {
          id: `auth-${studentId}-${Date.now()}`,
          student: student
        } : null
      }).filter(Boolean) as AuthorizedExperiment[]

      setExperiments(prevExperiments => 
        prevExperiments.map(exp => 
          exp.id === selectedExperiment
            ? {
                ...exp,
                authorizedExperiments: [...exp.authorizedExperiments, ...authorizedExperiments]
              }
            : exp
        )
      )

      setSuccess('学生授权成功')
      // 清除成功消息
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      setError(err.message || '授权失败')
    } finally {
      setLoading(false)
    }
  }

  // 取消学生授权
  const handleRevokeAuthorization = async (studentId: string) => {
    if (!selectedExperiment) return

    if (!confirm('确定要取消该学生的授权吗？')) return

    setLoadingStudentId(studentId)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(`/api/experiments/${selectedExperiment}/authorize`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          studentIds: [studentId],
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '取消授权失败')
      }

      // 更新本地状态
      setExperiments(prevExperiments => 
        prevExperiments.map(exp => 
          exp.id === selectedExperiment
            ? {
                ...exp,
                authorizedExperiments: exp.authorizedExperiments.filter(
                  authExp => authExp.student.id !== studentId
                )
              }
            : exp
        )
      )

      setSuccess('成功取消授权')
      // 清除成功消息
      setTimeout(() => setSuccess(''), 3000)
    } catch (err: any) {
      setError(err.message || '取消授权失败')
    } finally {
      setLoadingStudentId(null)
    }
  }

  return (
    <div className="mt-8 space-y-6">
      {/* 错误和成功提示 */}
      {error && (
        <div className="rounded-md bg-red-50 p-4 transition-all duration-300 ease-in-out">
          <div className="text-sm text-red-700">{error}</div>
        </div>
      )}
      
      {success && (
        <div className="rounded-md bg-green-50 p-4 transition-all duration-300 ease-in-out">
          <div className="text-sm text-green-700">{success}</div>
        </div>
      )}

      {/* 实验选择 */}
      <div className="bg-white shadow rounded-lg p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">选择实验</h2>
        <select
          value={selectedExperiment}
          onChange={(e) => setSelectedExperiment(e.target.value)}
          className="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
        >
          <option value="">请选择实验</option>
          {experiments.map((experiment) => (
            <option key={experiment.id} value={experiment.id}>
              {experiment.title}
            </option>
          ))}
        </select>
      </div>

      {/* 分组管理 */}
      {selectedExperiment && currentExperiment && (
        <>
          {/* 学生授权 */}
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-lg font-medium text-gray-900 mb-4">学生授权</h2>
            <p className="text-sm text-gray-600 mb-4">
              首先需要授权学生访问实验，然后才能将他们分配到小组中。
            </p>
            
            <div className="mb-4">
              <h3 className="text-sm font-medium text-gray-700 mb-2">
                已授权学生
                {loading && (
                  <span className="ml-2 text-xs text-gray-500">正在更新...</span>
                )}
              </h3>
              <div className="flex flex-wrap gap-2">
                {currentExperiment.authorizedExperiments.length === 0 ? (
                  <span className="text-sm text-gray-500">暂无授权学生</span>
                ) : (
                  currentExperiment.authorizedExperiments.map((authExp) => {
                    if (!authExp || !authExp.student) {
                      return null;
                    }
                    const studentName = authExp.student.name || '未知学生';
                    const studentEmail = authExp.student.email || '未知邮箱';
                    return (
                      <div key={authExp.student.id} className="flex items-center bg-blue-100 text-blue-700 px-2 py-1 rounded-full text-sm">
                        <UserIcon className="h-4 w-4 mr-1" />
                        {studentName} ({studentEmail})
                          <button
                          onClick={() => handleRevokeAuthorization(authExp.student.id)}
                          disabled={loading && loadingStudentId === authExp.student.id}
                          className="ml-2 text-red-500 hover:text-red-700 disabled:opacity-50"
                            title="取消授权"
                          >
                          {loading && loadingStudentId === authExp.student.id ? (
                            <svg className="animate-spin h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                              </svg>
                            ) : (
                            <XMarkIcon className="h-4 w-4" />
                            )}
                          </button>
                      </div>
                    );
                  })
                )}
              </div>
            </div>

            <div>
              <h3 className="text-sm font-medium text-gray-700 mb-2">授权新学生</h3>
              <div className="space-y-2 max-h-60 overflow-y-auto">
                {students.filter(student => 
                  !currentExperiment.authorizedExperiments.some(authExp => authExp.student.id === student.id)
                ).map((student) => (
                  <label key={student.id} className="flex items-center">
                    <input
                      type="checkbox"
                      value={student.id}
                      onChange={(e) => {
                        if (e.target.checked) {
                          handleAuthorizeStudents([student.id])
                        }
                      }}
                      disabled={loading}
                      className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded disabled:opacity-50"
                    />
                    <span className="ml-2 text-sm text-gray-700">
                      {student.name || student.email}
                    </span>
                  </label>
                ))}
              </div>
            </div>
          </div>

          {/* 分组列表 */}
          <div className="bg-white shadow rounded-lg p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-medium text-gray-900">分组列表</h2>
              <Button
                onClick={() => setShowCreateGroup(true)}
                className="inline-flex items-center"
              >
                <PlusIcon className="mr-2 h-4 w-4" />
                创建分组
              </Button>
            </div>

            {currentExperiment.groups.length === 0 ? (
              <p className="text-gray-500">暂无分组</p>
            ) : (
              <div className="space-y-4">
                {currentExperiment.groups.map((group) => (
                  <div key={group.id} className="border rounded-lg p-4">
                    <div className="flex items-center justify-between mb-2">
                      <div className="flex items-center">
                        <UserGroupIcon className="h-5 w-5 text-gray-400 mr-2" />
                        <h3 className="text-sm font-medium text-gray-900">{group.name}</h3>
                      </div>
                      <div className="flex items-center space-x-2">
                        <button
                          onClick={() => handleEditGroup(group)}
                          className="text-gray-600 hover:text-gray-900"
                          disabled={loading}
                          title="编辑分组"
                        >
                          <PencilIcon className="h-5 w-5" />
                        </button>
                        <button
                          onClick={() => handleDeleteGroup(group.id)}
                          className="text-red-600 hover:text-red-900"
                          disabled={loading}
                          title="删除分组"
                        >
                          <TrashIcon className="h-5 w-5" />
                        </button>
                      </div>
                    </div>
                    {group.description && (
                      <p className="text-sm text-gray-600 mb-2">{group.description}</p>
                    )}
                    <div className="flex flex-wrap gap-2">
                      {group.members.map((member) => (
                        <span
                          key={member.id}
                          className="inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-800"
                        >
                          {member.user.name || member.user.email}
                          {member.role === 'LEADER' && ' (组长)'}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 编辑分组对话框 */}
          {showEditGroup && editingGroup && (
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 max-w-md w-full">
                <h3 className="text-lg font-medium text-gray-900 mb-4">编辑分组</h3>
                
                <div className="space-y-4">
                  <div>
                    <label htmlFor="editGroupName" className="block text-sm font-medium text-gray-700">
                      分组名称
                    </label>
                    <input
                      type="text"
                      id="editGroupName"
                      value={groupName}
                      onChange={(e) => setGroupName(e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    />
                  </div>

                  <div>
                    <label htmlFor="editGroupDescription" className="block text-sm font-medium text-gray-700">
                      分组描述（可选）
                    </label>
                    <textarea
                      id="editGroupDescription"
                      value={groupDescription}
                      onChange={(e) => setGroupDescription(e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    />
                  </div>

                  <div>
                    <label htmlFor="editLeader" className="block text-sm font-medium text-gray-700">
                      选择组长
                    </label>
                    <select
                      id="editLeader"
                      value={selectedLeader}
                      onChange={(e) => setSelectedLeader(e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    >
                      {editingGroup.members.map(member => (
                        <option key={member.user.id} value={member.user.id}>
                          {member.user.name || member.user.email}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div className="mt-6 flex justify-end space-x-3">
                  <Button
                    variant="secondary"
                    onClick={() => {
                      setShowEditGroup(false)
                      setEditingGroup(null)
                      setGroupName('')
                      setGroupDescription('')
                      setSelectedLeader('')
                    }}
                  >
                    取消
                  </Button>
                  <Button
                    onClick={handleUpdateGroup}
                    disabled={loading}
                  >
                    {loading ? '更新中...' : '更新'}
                  </Button>
                </div>
              </div>
            </div>
          )}

          {/* 创建分组对话框 */}
          {showCreateGroup && (
            <div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
              <div className="bg-white rounded-lg p-6 max-w-md w-full">
                <h3 className="text-lg font-medium text-gray-900 mb-4">创建新分组</h3>
                
                <div className="space-y-4">
                  <div>
                    <label htmlFor="groupName" className="block text-sm font-medium text-gray-700">
                      分组名称
                    </label>
                    <input
                      type="text"
                      id="groupName"
                      value={groupName}
                      onChange={(e) => setGroupName(e.target.value)}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    />
                  </div>

                  <div>
                    <label htmlFor="groupDescription" className="block text-sm font-medium text-gray-700">
                      分组描述（可选）
                    </label>
                    <textarea
                      id="groupDescription"
                      value={groupDescription}
                      onChange={(e) => setGroupDescription(e.target.value)}
                      rows={3}
                      className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      选择学生
                    </label>
                    <div className="space-y-2 max-h-40 overflow-y-auto">
                      {getUnassignedStudents().map((student) => (
                        <label key={student.id} className="flex items-center">
                          <input
                            type="checkbox"
                            value={student.id}
                            checked={selectedStudents.includes(student.id)}
                            onChange={(e) => {
                              if (e.target.checked) {
                                setSelectedStudents([...selectedStudents, student.id])
                                // 如果是第一个选中的学生，自动设为组长
                                if (selectedStudents.length === 0) {
                                  setSelectedLeader(student.id)
                                }
                              } else {
                                setSelectedStudents(selectedStudents.filter(id => id !== student.id))
                                // 如果取消选中的是组长，清空组长选择
                                if (selectedLeader === student.id) {
                                  setSelectedLeader('')
                                }
                              }
                            }}
                            className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded"
                          />
                          <span className="ml-2 text-sm text-gray-700">
                            {student.name || student.email}
                          </span>
                        </label>
                      ))}
                    </div>
                  </div>

                  {selectedStudents.length > 0 && (
                    <div>
                      <label htmlFor="leader" className="block text-sm font-medium text-gray-700">
                        选择组长
                      </label>
                      <select
                        id="leader"
                        value={selectedLeader}
                        onChange={(e) => setSelectedLeader(e.target.value)}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                      >
                        <option value="">自动设置第一个学生为组长</option>
                        {selectedStudents.map(studentId => {
                          const student = students.find(s => s.id === studentId)
                          return student ? (
                            <option key={student.id} value={student.id}>
                              {student.name || student.email}
                            </option>
                          ) : null
                        })}
                      </select>
                    </div>
                  )}
                </div>

                <div className="mt-6 flex justify-end space-x-3">
                  <Button
                    variant="secondary"
                    onClick={() => {
                      setShowCreateGroup(false)
                      setGroupName('')
                      setGroupDescription('')
                      setSelectedStudents([])
                      setSelectedLeader('')
                    }}
                  >
                    取消
                  </Button>
                  <Button
                    onClick={handleCreateGroup}
                    disabled={loading}
                  >
                    {loading ? '创建中...' : '创建'}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  )
} 